package DesginFotmat;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.TwoPhaseStop")
public class TwoPhaseStop {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseInterrupt twoPhaseInterrupt = new TwoPhaseInterrupt();
        twoPhaseInterrupt.start();
        Thread.sleep(5000);
        //调用stop方法，实际上是调用interrupt通知线程需要打断
        twoPhaseInterrupt.stop();
    }
}


@Slf4j(topic = "c.TwoPhaseInterrupt")
class TwoPhaseInterrupt{
    //设计模式，两阶段终止，模拟监视器，interrupt并不会真的打断，而是通知线程需要打断，打断由线程本身决定
    private Thread mointor;//监视器线程
    public void start(){
        mointor = new Thread(() -> {
            Thread current = Thread.currentThread();
            while(true){
                //打断标记为true，线程处理交接事项之后，才停止监控任务
                if(current.isInterrupted()){
                    log.debug("线程被打断，处理后事，优雅退出");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("执行监视任务");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //睡眠期间被打断，interrupt标记仍为false，需重新打标记
                    current.interrupt();
                }
            }
        });
        mointor.start();
    }

    public void stop(){
        mointor.interrupt();
    }
}
